package com.hxzy.common.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

/**
 * 记录方法执行时间
 */
@Aspect
@Component
@Order(value = 1000)
public class StopWatchAspect {

    /**
     * 是否开启方法统计耗时
     */
    @Value(value = "${stopwatch.enable:false}")
    private boolean StopWatchEnabled;

    @Pointcut(value = "@annotation(com.hxzy.common.annon.StopWatch)")
    private void pointCutExpression(){
    }

    /**
     * 环境增强
     * @param pjp
     * @return
     */
    @Around(value = "pointCutExpression()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object proceed=null;

        if(StopWatchEnabled){
            String taskName=  pjp.getTarget().getClass().getSimpleName()+"."+pjp.getSignature().getName();
            StopWatch stopWatch=new StopWatch(taskName);
            stopWatch.start();
            //反射调用方法
             proceed = pjp.proceed();
            stopWatch.stop();
            System.out.println(stopWatch.shortSummary());
            System.out.println(stopWatch.prettyPrint());
        } else{
            //反射调用方法
            proceed = pjp.proceed();
        }
        return proceed;
     }

}
